package com.santiao.youxiang.ui.activity

//import com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
//import kotlin.jvm.java

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ArrayAdapter
import android.widget.ListPopupWindow
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.gyf.immersionbar.ImmersionBar
import com.santiao.publics.ui.SettingFragment
import com.santiao.publics.ui.WebViewActivity
import com.santiao.youxiang.MainActivity
import com.santiao.youxiang.bean.PostBean
import com.santiao.youxiang.database.hleper.PostDatabaseHelper
import com.santiao.youxiang.databinding.ActivityAddPostBinding
import com.santiao.youxiang.ext.thrillClickListener
import com.santiao.youxiang.ui.fragment.HomeViewModel
import com.santiao.youxiang.ui.widget.LoadingDiaLog
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.leefeng.promptlibrary.PromptButton
import me.leefeng.promptlibrary.PromptDialog
import java.util.Properties
import javax.mail.Session
import kotlin.toString

class AddAccountActivity: AppCompatActivity() {
    private lateinit var binding: ActivityAddPostBinding
//    private lateinit var lzyadsUtils: com.lazyliuzy.commonui.utils.lzy.LZYADSUtils
var type_a="" //1 qq 2：163 3:126

    val eamillist = listOf("@qq.com", "@163.com", "@126.com")
    val htttplist = listOf("https://service.mail.qq.com/detail/0/75",
        "https://help.mail.163.com/faqDetail.do?code=d7a5dc8471cd0c0e8b4b8f4f8e49998b374173cfe9171305fa1ce630d7f67ac286624f309a1a7089",
        "https://help.mail.163.com/faqDetail.do?code=d7a5dc8471cd0c0e8b4b8f4f8e49998b374173cfe9171305fa1ce630d7f67ac286624f309a1a7089")
//    private val HviewModel: HomeViewModel by viewModels()
private lateinit var HviewModel: HomeViewModel



    var slePosition=1

    var emailSuffix=""
    private var buttonAble=true

    var struri=""
    // 在类顶部定义
    val REQUEST_STORAGE_PERMISSION = 1001  // 可以是任意唯一整数



    companion object {
        // 定义一个静态方法来创建Intent
        // 定义一个静态方法来创建Intent并携带uri数据
        fun startActivity(context: Context?, type: String) {

            val intent = Intent(context, AddAccountActivity::class.java).apply {

                putExtra("type", type)

            }

            context!!.startActivity(intent)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityAddPostBinding.inflate(layoutInflater)
        setContentView(binding?.root)
        type_a= intent.getStringExtra("type").toString()
        ImmersionBar.with(this)
            .transparentStatusBar()
            .statusBarDarkFont(true)
            .transparentNavigationBar()
            .init()
        initViews(type_a)
//        HviewModel = ViewModelProvider(this@AddAccountActivity).get(HomeViewModel::class.java)
        HviewModel= MainActivity.HviewModel

        SettingFragment.adLoad2(0,null,binding.flContent3,this,this)
    }



     fun initViews(type: String) {
//        initad()
         binding.tvEmail.text=eamillist[type.toInt()-1]
         emailSuffix=eamillist[type.toInt()-1]
         initclick()


        binding.toolbarBack.setOnClickListener { onBackPressed() }



    }

//    private fun updateButtonState(){
//        if (binding.editAddress.text.isNotBlank()&&binding.editPassword.text.isNotBlank()){
////            binding.textCarSave.setBackgroundResource(R.drawable.bg_color_greenab_radius_500)
//            buttonAble=true
//        }else{
////            binding.textCarSave.setBackgroundResource(R.drawable.bg_color_greenun_radius_500)
//            buttonAble=false
//        }
//    }

    fun initclick(){


//        val context = this@AddAccountActivity
//        val popup = PopupMenu(context, binding.llWithCom)
//        popup.menuInflater.inflate(R.menu.menu_cam_item, popup.menu)
//        popup.setOnMenuItemClickListener { menuItem ->
////            emailSuffix=menuItem.title.toString().trimStart()
//            when (menuItem.itemId) {
//                R.id.action_qq -> {
//                    emailSuffix=menuItem.title.toString().trimStart()
//
//                    true
//                }
//                R.id.action_163 -> {
//                    emailSuffix=menuItem.title.toString().trimStart()
//
//                    true
//                }
//
//                R.id.action_126 -> {
//                    emailSuffix=menuItem.title.toString().trimStart()
//
//                    true
//                }
//                else -> false
//            }
//        }


        binding.tvHelp.thrillClickListener {


            val promptDialog = PromptDialog(this@AddAccountActivity);
            val cancel = PromptButton("取消", null)
            cancel.textColor = Color.parseColor("#0076ff")
            cancel.textSize=16f
            val quit= PromptButton("QQ邮箱") {
                WebViewActivity.gotoActivity(this@AddAccountActivity, "如何获取授权码?", htttplist[0])
            }
            val keep= PromptButton("163邮箱/126邮箱"){
                WebViewActivity.gotoActivity(this@AddAccountActivity, "如何获取授权码?", htttplist[1])
            }
            cancel.textSize=16f
            quit.textSize=16f
            keep.textSize=16f
//            keep.textColor=Color.RED
            promptDialog.showAlertSheet(
                "", true, cancel,
                keep,
                quit
            )

        }

        binding.editAddress.onFocusChangeListener =
            View.OnFocusChangeListener { v, hasFocus ->
                if (!hasFocus) {
                    if (binding.editAddress.text.isNullOrBlank()){
                        Toast.makeText(this@AddAccountActivity,"输入邮件地址不能为空！", Toast.LENGTH_SHORT).show()
                    }else{
                        val emailPattern = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:qq\\.com|126\\.com|163\\.com|aliyun\\.com)$"
                        val currentText = binding.editAddress.text.toString()+emailSuffix
                        // 如果输入不符合邮件格式，可以做提示或其他处理
                        if (!currentText.matches(emailPattern.toRegex())) {
                            Toast.makeText(this@AddAccountActivity,"请输入有效的邮件地址！", Toast.LENGTH_SHORT).show()
                            binding.editAddress.setText("")
                        }
                    }
//                    updateButtonState()
                }
            }
        binding.editAddress.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER)) {
                if (binding.editAddress.text.isNullOrBlank()){
                    Toast.makeText(this@AddAccountActivity,"输入邮件地址不能为空！", Toast.LENGTH_SHORT).show()
                }else{
                    val emailPattern = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:qq\\.com|126\\.com|163\\.com|aliyun\\.com)$"
                    val currentText = binding.editAddress.text.toString()+emailSuffix
                    // 如果输入不符合邮件格式，可以做提示或其他处理
                    if (!currentText.matches(emailPattern.toRegex())) {
                        Toast.makeText(this@AddAccountActivity,"请输入有效的邮件地址！", Toast.LENGTH_SHORT).show()
                        binding.editAddress.setText("")
                    }
                }
//                updateButtonState()
            }
            false
        }
        //name
        binding.editPassword.onFocusChangeListener =
            View.OnFocusChangeListener { v, hasFocus ->
                if (!hasFocus) {
//                    updateButtonState()
                }
            }
        binding.editPassword.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.keyCode == KeyEvent.KEYCODE_ENTER)) {
//                updateButtonState()
            }
            false
        }

        binding.textCarSave.thrillClickListener{

            if (binding.editAddress.text.toString().isNullOrEmpty()||binding.editPassword.text.toString().isNullOrEmpty()){
                Toast.makeText(this@AddAccountActivity,"账号或授权码未填写",Toast.LENGTH_SHORT).show()
                return@thrillClickListener
            }

                if(PostDatabaseHelper(this@AddAccountActivity,HviewModel).isPostAddressExists(binding.editAddress.text.toString()+emailSuffix)){
                    Toast.makeText(this@AddAccountActivity,"请勿重复添加邮箱",Toast.LENGTH_SHORT).show()
                    Log.e("initclick: ", "重复添加")
                }else{
//                    val advDiaLog = LoadingDiaLog(this@AddAccountActivity,"加载中...")
//                    advDiaLog.show()
                    Log.e("initclick: ", "加载中")
                    tryToLoginEmail(binding.editAddress.text.toString()+emailSuffix,binding.editPassword.text.toString())

                }

            SettingFragment.adLoad3(0,null,null,this,this);
        }

        binding.llWithCom.thrillClickListener {
//            if (isActivityAlive(this)) {
//                showListPopup()
//            }
            showListPopup()
        }


    }


    fun showListPopup() {
        val anchor = binding.llWithCom

        val popup = ListPopupWindow(this@AddAccountActivity).apply {
            setAdapter(ArrayAdapter(
                this@AddAccountActivity,
                android.R.layout.simple_list_item_1,
                listOf("@qq.com", "@163.com", "@126.com")
            ))
            this.anchorView = anchor

            // 0 表示和 anchor 左对齐／右对齐都可，视需求改成 anchor.width - popupWidth/2 之类
            horizontalOffset = 0

            // 纵向偏移 10dp
            verticalOffset = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                10f,
                resources.displayMetrics
            ).toInt()

            // 宽度设为 anchor 宽度
            width = anchor.width

            // 可选：高度自适应，也可以写一个固定值
            height = ListPopupWindow.WRAP_CONTENT

            isModal = true  // 点击外面可以 dismiss
        }

        // 监听点击
        popup.setOnItemClickListener { parent, _, position, _ ->
            // TODO: 处理点击



           emailSuffix = parent.getItemAtPosition(position) as String
            emailSuffix=emailSuffix.trimStart()
            binding.tvEmail.text=emailSuffix
//            emailSuffix=adapter[position].toString().trimStart()
            popup.dismiss()
        }

        popup.show()
    }

    /*fun showListPopup() {
        val anchor = binding.llWithCom
        val items = listOf("@qq.com", "@163.com", "@126.com")

        // Ensure the anchor view is properly initialized before showing the popup
        if (anchor.isAttachedToWindow) {
            val popup = ListPopupWindow(this@AddAccountActivity).apply {
                setAdapter(ArrayAdapter(
                    this@AddAccountActivity,
                    android.R.layout.simple_list_item_1,
                    items
                ))
                this.anchorView = anchor

                // 0 表示和 anchor 左对齐／右对齐都可，视需求改成 anchor.width - popupWidth/2 之类
                horizontalOffset = 0

                // 纵向偏移 10dp
                verticalOffset = TypedValue.applyDimension(
                    TypedValue.COMPLEX_UNIT_DIP,
                    10f,
                    resources.displayMetrics
                ).toInt()

                // 宽度设为 anchor 宽度
                width = anchor.width

                // 可选：高度自适应，也可以写一个固定值
                height = ListPopupWindow.WRAP_CONTENT

                isModal = true  // 点击外面可以 dismiss
            }

            // 监听点击
            popup.setOnItemClickListener { parent, _, position, _ ->
                // TODO: 处理点击
                emailSuffix = parent.getItemAtPosition(position) as String
                emailSuffix = emailSuffix.trimStart()
                popup.dismiss()
            }

            // Check if the view is ready and then show
            anchor.viewTreeObserver.addOnPreDrawListener {
                popup.show()
                true
            }
        } else {
            // Handle case when anchor is not attached
            Log.e("Popup", "Anchor view is not attached to the window.")
        }
    }*/



    fun switchItem(position: Int) {

    }






    fun   initad() {
//        myContext = requireContext()
//        lzyadsUtils=
//            com.lazyliuzy.commonui.utils.lzy.LZYADSUtils("Task1Activity", this@Task1Activity)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.loadSimpleAd1(com.lazyliuzy.commonui.databinding.ActivityTask1Binding.flAd)
//        com.lazyliuzy.commonui.utils.lzy.LZYADSUtils.showAdCpTurn()

    }

    @OptIn(DelicateCoroutinesApi::class)
    fun tryToLoginEmail( email: String, authCode: String) {
        Log.e( "tryToLoginEmail:@  ",email )
        val loadingDiaLog= LoadingDiaLog(this@AddAccountActivity,"连接中...")
        loadingDiaLog.show()
        // 在后台线程执行 IMAP 请求
        GlobalScope.launch(Dispatchers.IO) {
            var imapHost: String? =null
            val domain = email.substringAfter("@")
            when (domain) {
                "126.com" -> {
                    imapHost = "imap.126.com"
                }

                "163.com" -> {
                    // 对136.com进行处理
                    imapHost = "imap.163.com"
                }

                "qq.com" -> {
                    // 对qq.com进行处理
                    imapHost = "imap.qq.com"
                }

                else -> {
                    imapHost = "imap.aliyun.com"
                }
            }
            val imapPort = "993"
            val properties = Properties()
            properties["mail.store.protocol"] = "imaps"
            properties["mail.imaps.host"] = imapHost
            properties["mail.imaps.port"] = imapPort
            properties["mail.imap.ssl.enable"] = "true"

            // 获取Session
            val session = Session.getInstance(properties)
            try {
                // 创建 IMAP 存储连接
                val store = session.getStore("imaps")
                store.connect(imapHost, email, authCode)  // 使用授权码登录
                store.close()
                withContext(Dispatchers.Main) {
                    val databaseHelper=PostDatabaseHelper(this@AddAccountActivity,HviewModel)
                    val oldCurrent=databaseHelper.getCurrentPost()
                    var newCurrentId=-1L
                    if (oldCurrent==null){
                        newCurrentId=databaseHelper.insertPost(PostBean(null,email,authCode,true))
                        Log.e("tryToLoginEmail:空 ", newCurrentId.toString())
                    }
                    else{
                        Log.e("tryToLoginEmail: ", "1")
                        databaseHelper.updatePost(PostBean(oldCurrent.pid,oldCurrent.pAddress,oldCurrent.pCode,false))
                        newCurrentId=databaseHelper.insertPost(PostBean(null,email,authCode,true))
                        Log.e("tryToLoginEmail: ", "更新")
                    }
                    HviewModel.currentPost.value=newCurrentId
                    Log.e("tryToLoginEmail:currentPost ", newCurrentId.toString())
                    loadingDiaLog.dismiss()
//                    Toast.makeText(this@AddAccountActivity,"登录连接成功~",Toast.LENGTH_SHORT).show()
                    when (domain) {
                        "126.com" -> {
                            HviewModel.currentPostType.value="126"
                        }

                        "163.com" -> {
                            // 对136.com进行处理
                            HviewModel.currentPostType.value="163"
                        }

                        "qq.com" -> {
                            // 对qq.com进行处理
                            HviewModel.currentPostType.value="qq"
                        }

                        else -> {
                            HviewModel.currentPostType.value="aliyun"
                        }
                    }
//                    lzyadsUtils.showAdCpTurn()
//                    finish()
                    MainActivity.gotoActivity(this@AddAccountActivity)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Log.e( "tryToLoginEmail: ",e.toString() )
//                LZYLog.i("lzyemail", "邮件：登录连接失败")
                withContext(Dispatchers.Main) {
                    loadingDiaLog.dismiss()
                    Toast.makeText(this@AddAccountActivity,"登录连接失败！",Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun hideKeyboard(view: View) {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    fun initdata(){}

}